/*
 * Copyright (c) 2022-2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import common from '@ohos.app.ability.common'
import consts from '../module/Consts'
import dataPreferences from '@ohos.data.preferences'
import Logger from '../module/Logger'

const TAG: string = '[Sample_CustomCommonEvent_HistoryFeature]'

export default class HistoryFeature {
  constructor(abilityContext: common.UIAbilityContext) {
    this.innerContext = abilityContext
  }

  async getData() {
    await this.init()
    return new Promise((resolve) => {
      resolve(this.dataSource)
    })
  }

  private async init() {
    let prefer = null
    await dataPreferences.getPreferences(this.innerContext, consts.DATA_BASE_NAME).then((pref) => {
      prefer = pref
    })
    let records: Array<string>
    await prefer.get(consts.DATA_BASE_KEY_TOTAL_TIMES, []).then((value: Array<string>) => {
      records = value
    })
    for (let item of records) {
      await prefer.get(item, []).then((detail: Array<string>) => {
        if(JSON.stringify(detail) !== '[]'){
          this.dataSource.push(detail)
        }
      }).catch((error)=>{
        Logger.info(TAG, `Failed to get value code is ${error.code}`)
      })
    }
  }

  private dataSource: Array<Array<string>> = []
  private innerContext: common.UIAbilityContext = null
}